package com.example.shiro.config;

import com.example.shiro.bean.User;
import com.example.shiro.map.UserMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Jiange
 * @create 2021-05-07-16:24
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserMap userMap;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        simpleAuthorizationInfo.addStringPermission("user----add");
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();

        simpleAuthorizationInfo.addStringPermission(currentUser.getPerms());
        System.out.println("授权");
        return simpleAuthorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String username = token.getUsername();

        User byUsername = userMap.getByUsername(username);
//        if (!token.getUsername().equals("root")){
//            return null;//会自动抛出异常 UnknownAccountException
//        }
        if(byUsername == null){
            return null;
        }
        String passWord = byUsername.getPassWord();
        byUsername.setPerms("user----add");
        return new SimpleAuthenticationInfo(byUsername,passWord,"");
    }
}
